//
//  WKHomeViewController.m
//  WeKeTang
//
//  Created by ichina on 2017/8/22.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKHomeViewController.h"
#import "WKDrawerViewController.h"
#import "WKSearchViewController.h"
#import "WKNavgationController.h"
#import "WKDownLoadViewController.h"
#import "WKPlayerViewController.h"
#import "WKProfireViewController.h"
#import "ScottAlertView.h"
#import "ScottAlertViewController.h"
#import "AppDelegate.h"
#import "WKLoginHandel.h"
#import "WKAlerView.h"
#import "HMScannerController.h"
#import "MyJSObject.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "WKNetworkTools.h"
#import "WKFMDBTools.h"
#import "WKDownLoadModel.h"
#import "NSString+KZExtension.h"
#import "GCDWebServer.h"
#import "WKDownLoadManger.h"
@interface WKHomeViewController ()<UIWebViewDelegate,MyJSObjectDelegate>

@property (nonatomic, strong) UIButton *btnUser;
@property (nonatomic, strong) UILabel *redLabel;
@property (nonatomic, strong) UITextField *TFsearch;
@property (nonatomic, strong) UIButton *btnBack;
@property (nonatomic, strong) UIButton *imgSearch;
@property (nonatomic, strong) UIButton *btnSearch;
@property (nonatomic, strong) UIButton *downBtn;
@property (nonatomic, strong) UIButton *btnScaner;//二维码
@property (nonatomic, strong) UIButton *btnClose;
@property (nonatomic, strong) WKAlerView *alertView;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;//进度条
@property (nonatomic, strong) JSContext *context;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) WKFMDBTools *dbManger;
@property (nonatomic, strong) GCDWebServer *webServer;
@property (nonatomic, strong) NSDictionary *dict;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, copy) NSString *section_voiceid;
@property (nonatomic, copy) NSString *section_name;
@property (nonatomic, assign) BOOL isDownloading;
@property (nonatomic, assign) NSInteger reachabilityStatus;
@property (nonatomic, strong) NSOperationQueue *mainQueue;
@property (nonatomic, strong) NSBlockOperation *main0peration;
@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, strong) NSBlockOperation *operation;
@property (nonatomic, assign) NSInteger downLoadCount;
@property (nonatomic, strong) AFURLSessionManager *downLoadSession;
@property (nonatomic, assign) BOOL  downLoadRecode;

@end

@implementation WKHomeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadMessageCount];
    
    [self setupUI];
    
    if (_isCollection) {
        self.navgationBar.hidden = YES;
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(messageAction) name:@"message" object:nil];
   _reachabilityStatus =  [AppDelegate shareDelegate].reachabilityStatus;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _isCollection = NO;
}
- (void)messageAction{
    
    self.redLabel.hidden = YES;
}

- (void)setupUI{
    self.index = 0;
    self.navgationBar.barTintColor = RGBColor(40, 188, 203);
    self.statusbar.backgroundColor = RGBColor(40, 188, 203);

    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, kDeviceScreenWidth, kDeviceScreenHeight-64)];
//    self.webView.navigationDelegate = self;
//    self.webView.UIDelegate =self;
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    //TODO: 添加进度条
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, kDeviceScreenWidth, 1)];
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 0.6f);
    self.progressView.backgroundColor = RGBColor(84, 178, 240);
    self.progressView.progressTintColor = [UIColor yellowColor];
    self.progressView.hidden = YES;
    self.progressView.trackTintColor = [UIColor whiteColor];
    [self.view addSubview:self.progressView];
    [self.navgationBar addSubview:self.btnUser];
    [self.navgationBar addSubview:self.redLabel];
    self.redLabel.hidden = YES;
    [self.navgationBar addSubview:self.TFsearch];
    [self.navgationBar addSubview:self.downBtn];
    [self.navgationBar addSubview:self.btnScaner];
    [self.navgationBar addSubview:self.btnBack];
    [self.navgationBar addSubview:self.btnClose];
    self.btnBack.hidden = YES;
    self.btnClose.hidden = YES;
    [self.TFsearch addSubview:self.imgSearch];
    [self.TFsearch addSubview:self.btnSearch];
    
    NSURL *url;
    if (_isCollection) {
        url = [NSURL URLWithString:self.urlStr];
    }else if (_isCanner){
        url = [NSURL URLWithString:self.urlStr];
    }else{
        NSMutableString *urlStr = [[NSMutableString alloc]initWithString:kH5Str];
        [urlStr appendString:self.userId];
        url = [NSURL URLWithString:urlStr];
    }
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didCreateJSContext:) name:@"DidCreateContextNotification" object:nil];
    
    //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playeVideo:) name:@"playVideo" object:nil];
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(downLoad:) name:@"downLoad" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(supendDownload) name:@"supend" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(continueDownload:) name:@"continuedown" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(backJSAction:) name:@"backAction" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openMemberAction:) name:@"openMember" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(collectionAction:) name:@"collectionControl" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushProfireVCAction:) name:@"pushProfireVC" object:nil];
    
    self.dbManger = [WKFMDBTools defaultFMDBToos];
    [[AppDelegate shareDelegate] addObserver:self forKeyPath:@"reachabilityStatus" options:0 context:NULL];
    //初始化数据库
//    [self.dbManger creatTable];
}
//kvo监听信号变化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"reachabilityStatus"]) {
        
        _reachabilityStatus = [AppDelegate shareDelegate].reachabilityStatus;
        NSLog(@" 当前网络状态:%ld",_reachabilityStatus);
    }
}
#pragma mark - MyJSObjectDelegate播放
- (void)MyJSObject:(MyJSObject *)MyJSObject dict:(NSDictionary *)dict{

    switch (_reachabilityStatus) {
        case 0:
            [self showCustomAlertMessage:@"当前无网络"];
            break;
        case 1:
            [self ReachableViaWWANPlayerWithDict:dict];//移动网络
            break;
        case 2:
            [self ReachableViaWiFiWithDict:dict];
            break;
        default:
            break;
    }
    
   
}
#pragma mark - 移动网络播放
- (void)ReachableViaWWANPlayerWithDict:(NSDictionary*)dict{
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self showIndicatorWithFlag:YES title:@"视频加载中..."];
//    });
//    
    __weak typeof(self) weakSelf = self;
    self.alertView = [[WKAlerView alloc]initWithFrame:[UIScreen mainScreen].bounds message:@"当前正在3G/4G状态下,如观看需要消耗您的流量!" tip:@"" title1:@"确定" title2:@"取消"];
    self.alertView.isPlayer = YES;
    self.alertView.confirmBlock = ^{
        //执行删除操作
        weakSelf.dict = dict;
        [weakSelf.timer invalidate];
        weakSelf.timer = nil;
        NSLog(@"timer：%@",weakSelf.timer);
        weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:weakSelf selector:@selector(playerVideoWithDic:) userInfo:nil repeats:NO];
        
        [weakSelf.alertView removeFromSuperview];
    };
    self.alertView.cancelBlock = ^{
        
        [weakSelf.alertView removeFromSuperview];
    };
    self.alertView.deleteBlock = ^{
    
        [weakSelf.alertView removeFromSuperview];
    };
     [[UIApplication sharedApplication].keyWindow addSubview:self.alertView];

}
#pragma mark - WIFI情况下播放
- (void)ReachableViaWiFiWithDict:(NSDictionary*)dict{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showIndicatorWithFlag:YES title:@"视频加载中..."];
    });
    self.dict = dict;
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"timer：%@",self.timer);
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(playerVideoWithDic:) userInfo:nil repeats:NO];
    
}

- (void)playerVideoWithDic:(NSDictionary*)dic{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = self.dict;
    NSLog(@"播放参数:%@",dict);
    NSString *typeid = [self changeCgrade:dict[@"cgrade"]];
    NSString *placeholderImage = [NSString stringWithFormat:@"%@%@",kTestMainUrl,dict[@"section_imgurl"]];
    NSString *section_name = dict[@"section_name"];
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *mac = [WKUniversal macaddress];
    NSString *phpsessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"getnewplayurl" forKey:@"commandid"];
    [para setObject:dict[@"section_videoid"] forKey:@"videoid"];
    [para setObject:typeid forKey:@"typeid"];
    [para setObject:@"1" forKey:@"type"];
    [para setObject:dict[@"courseid"] forKey:@"courseid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:phpsessid forKey:@"phpsessid"];
    [para setObject:mac forKey:@"mac"];
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    
    [[WKNetworkTools shareManger]RunNoneRequest:para path:kServerDomain tip:nil completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSDictionary *headDict = dic[@"head"];
        NSDictionary *bodyDict = dic[@"body"];
        NSString *statuscode = headDict[@"statuscode"];
        NSString *vurl = bodyDict[@"vurl"];
        if ([statuscode intValue] == 100) {
            [self showIndicatorWithFlag:NO title:@""];
            WKPlayerViewController *playerVC = [[WKPlayerViewController alloc]init];
            playerVC.vurl = vurl;
            playerVC.placeholderImage = placeholderImage;
            playerVC.section_name = section_name;
            playerVC.section_videoid = dict[@"section_videoid"];
            [weakSelf.timer invalidate];
            weakSelf.timer = nil;
            playerVC.backBlock = ^{
                [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
                
            };
            playerVC.block = ^(NSInteger currentTime, NSInteger totalTime) {
                NSLog(@"----%ld-----%ld",(long)currentTime,(long)totalTime);
                [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
                //拿到数据库观看数据进行对比
                NSMutableArray *watchList = [NSMutableArray array];
                watchList = [weakSelf.dbManger QueryWatchDataWithTableName:kDBWatchTableName section_videoid:dict[@"section_videoid"]];
                
                if (watchList.count == 0) {
                    //播放接口 插入观看数据
                    [weakSelf.dbManger InsertWatchDataWithVurl:vurl Cgrade:dict[@"cgrade"] section_name:dict[@"section_name"] section_imgurl:dict[@"section_imgurl"] section_videoid:dict[@"section_videoid"] courseid:dict[@"courseid"] stimes:dict[@"stimes"] status:@"" totalTime:[NSString stringWithFormat:@"%ld",(long)totalTime] currentTime:[NSString stringWithFormat:@"%ld",currentTime]];
                }else{
                    //播放接口 更新数据
                    NSLog(@"---------------%@",dict[@"section_videoid"]);
                    [weakSelf.dbManger UpdateWatchDataWithTabelName:kDBWatchTableName vurl:vurl cgrade:dict[@"cgrade"] section_name:dict[@"section_name"]  section_imgurl:dict[@"section_imgurl"] courseid:dict[@"courseid"] stimes:dict[@"stimes"] status:@"" totalTime:[NSString stringWithFormat:@"%ld",(long)totalTime] currentTime:[NSString stringWithFormat:@"%ld",currentTime] section_videoid:dict[@"section_videoid"]];
                }
            };
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
            [weakSelf.navigationController pushViewController:playerVC animated:YES];
        }else{
            //[weakSelf showCustomAlertMessage:@"视频地址错误"];
        }
        NSLog(@"播放接口:%@",dic);
    }];
    
}
#pragma mark - 点击第一个轮播图 跳到个人中心
- (void)pushProfireVCAction:(NSNotification*)nofi{
    WKProfireViewController *profireVC = [[WKProfireViewController alloc]init];
    WKNavgationController *nav = [[WKNavgationController alloc] initWithRootViewController: profireVC];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:nav animated:YES completion:nil];
    });
    NSLog(@"个人中心：%@",nofi.userInfo);
}
#pragma mark - 获取消息个数
- (void)loadMessageCount{
    
    __weak typeof(self) weakSelf = self;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"noticenews" forKey:@"commandid"];
    [para setObject:userid forKey:@"userid"];
    
    NSLog(@"消息参数:%@",para);
    
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunNoneRequest:para path:kServerDomain tip:nil completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
       // [weakSelf showCustomAlertMessage:@"网络错误"];
    } finishHandler:^(id responseObject) {
        
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *head = dict[@"head"];
        NSString *body = dict[@"body"];
        NSString *statusCode = head[@"statuscode"];
        if ([statusCode intValue] == 100) {
            
        }
        if ([body intValue] == 1) {
            
            weakSelf.redLabel.hidden = NO;
        }else if ([body intValue] == 0){
            
            weakSelf.redLabel.hidden = YES;
        }
        
    }];
    
}
- (void)dealloc{
    [[AppDelegate shareDelegate] removeObserver:self forKeyPath:@"reachabilityStatus"];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


#pragma mark - 收藏
- (void)collectionAction:(NSNotification*)nofi{
     NSDictionary *dict = nofi.userInfo;
    NSString *status = dict[@"str"];
    dispatch_async(dispatch_get_main_queue(), ^{
       [self showCustomAlertMessage:status];
    });
}
#pragma mark - 开通会员
- (void)openMemberAction:(NSNotification*)nofi{
//    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
//    if ([userid isEqualToString:@"1469149"]) {
//        [self showCustomAlertMessage:@"您当前是游客身份,请先注册会员!"];
//        return;
//    }
    __weak typeof(self) weakSelf = self;
     NSDictionary *dict = nofi.userInfo;
    NSString *status = [NSString stringWithFormat:@"%@",dict[@"str"]];
    dispatch_async(dispatch_get_main_queue(), ^{
        WKMemberController *memberVC = [[WKMemberController alloc]init];
        memberVC.isOpen = YES;
        memberVC.status = status;
        [weakSelf.navigationController pushViewController:memberVC animated:YES];
    });
   
    
}
#pragma mark - 下载
- (void)MyJSObject:(MyJSObject *)MyJSObject downloadDict:(NSDictionary *)downloadDict{
    if (_downLoadRecode) {
        [self showCustomAlertMessage:@"当前有正在下载任务,暂不支持多任务下载!"];
        return;
    }
    _isDownloading = NO;
    _index = 0;
    NSLog(@"下载视频%@",downloadDict);
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = downloadDict;
    //    NSLog(@"播放参数:%@",dict);
    NSString *typeid = [self changeCgrade:dict[@"cgrade"]];
    //NSString *placeholderImage = [NSString stringWithFormat:@"%@%@",kMainUrl,dict[@"section_imgurl"]];
    NSString *section_name = dict[@"section_name"];
    self.section_name = section_name;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *mac = [WKUniversal macaddress];
    NSString *phpsessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"getnewplayurl" forKey:@"commandid"];
    [para setObject:dict[@"section_videoid"] forKey:@"videoid"];
    [para setObject:typeid forKey:@"typeid"];
    [para setObject:@"2" forKey:@"type"];
    [para setObject:dict[@"courseid"] forKey:@"courseid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:phpsessid forKey:@"phpsessid"];
    [para setObject:mac forKey:@"mac"];
    self.section_voiceid = dict[@"section_videoid"];
    NSLog(@"下载参数%@",para);
    
    self.mainQueue = [[NSOperationQueue alloc] init];
    //2.创建NSBlockOperation对象
    self.main0peration = [NSBlockOperation blockOperationWithBlock:^{
        [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
        [[WKNetworkTools shareManger]RunNoneRequest:para path:kServerDomain tip:nil completionHandler:^(id responseObject) {
            NSLog(@"下载错误%@",responseObject);
        } errorHandler:^(NSError *error) {
            
            NSLog(@"下载错误%@",error);
        } finishHandler:^(id responseObject) {
            NSDictionary *dic = [responseObject mj_JSONObject];
            NSLog(@"下载接口:%@",dic);
            NSDictionary *headDict = dic[@"head"];
            NSDictionary *bodyDict = dic[@"body"];
            NSString *statuscode = headDict[@"statuscode"];
            NSString *vurl = bodyDict[@"vurl"];
            
            if ([statuscode intValue] == 100) {
                //查询数据库
                BOOL isDownLoad = NO;
                NSMutableArray *downLoadList = [NSMutableArray array];
                downLoadList = [weakSelf.dbManger QueryDataWithKey:@"DownloadList"];
                if (downLoadList.count == 0) {
                    isDownLoad = YES;
                    [weakSelf showCustomAlertMessage:@"您已开启下载任务,任务已添加到下载队列"];
                }else{
                    for (NSInteger i = 0; i<downLoadList.count; i++) {
                        WKDownLoadModel *model = downLoadList[i];
                        
                        if ([model.section_videoid isEqualToString:dict[@"section_videoid"]]) {
                            
                            [weakSelf showCustomAlertMessage:@"此任务已在下载任务队列中！"];
                            return ;
                        }else{
                            isDownLoad = YES;
                            [weakSelf showCustomAlertMessage:@"您已开启下载任务,任务已添加到下载队列"];
                        }
                    }
                }
                NSLog(@"查询到的数据%@",downLoadList);
                //开始下载
                if (isDownLoad) {
                    [weakSelf startDownLoadVideoWithDict:dict vurl:vurl];
                }
                
            }else{
                //[weakSelf showCustomAlertMessage:@"视频地址错误"];
            }
        }];
        
    }];
    [self.main0peration addExecutionBlock:^{
        
    }];
    self.mainQueue.maxConcurrentOperationCount = 1;
    //4.队列添加任务
    [self.mainQueue addOperation:weakSelf.main0peration];
    
    // [weakSelf.main0peration start];
}

#pragma mark - 开始下载
- (void)startDownLoadVideoWithDict:(NSDictionary*)dict vurl:(NSString *)vurl{
    
    __weak typeof(self) weakSelf = self;
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@video",dict[@"section_name"]]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    NSError *err;
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",@"order.m3u8"]];
    NSLog(@"本地路径-----%@",path);
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]DownloadFileFrom:vurl toFile:path completionHandler:^(NSString *filePath) {
        NSString *content = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        //        NSLog(@"本地路径2%@",content);
        //使用正则表达式把所有的.ts地址保存起来
        NSString *regulaStr = @"\\bhttp?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
        NSError *error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error];
        NSArray *arrayOfAllMatches = [regex matchesInString:content options:0 range:NSMakeRange(0, [content length])];
        NSString *pathV = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        pathV = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@video",dict[@"section_name"]]];
        weakSelf.downLoadCount = arrayOfAllMatches.count;
        NSLog(@"片段总个数:%ld",arrayOfAllMatches.count);
        [weakSelf.dbManger InsertDataWithVurl:vurl Cgrade:dict[@"cgrade"] section_name:dict[@"section_name"] section_imgurl:[NSString stringWithFormat:@"%@%@",kTestMainUrl,dict[@"section_imgurl"]] section_videoid:dict[@"section_videoid"] courseid:dict[@"courseid"] stimes:dict[@"stimes"] status:@"downLoading" currentWatchCount:@"0" totalWatchCount:@""  completeCount:@"" totalCount:[NSString stringWithFormat:@"%ld",arrayOfAllMatches.count] currentUrl:@"temp"];
        for (NSInteger i = 0; i<arrayOfAllMatches.count; i++) {
            NSTextCheckingResult *match = arrayOfAllMatches[i];
            NSString* substringForMatch = [content substringWithRange:match.range];
            
            //获取到地址下载视频
            [weakSelf downloadWithUrl:substringForMatch txt:content path:pathV index:i subString:substringForMatch downLoadCount:arrayOfAllMatches.count name:dict[@"section_name"] section_videoid:dict[@"section_videoid"]];
        }
    } errorHandler:^(NSError *error) {
    
    }];
}
#pragma mark - 下载ts文件
- (void)downloadWithUrl:(NSString *)url txt:(NSString *)txt path:(NSString*)path index:(NSInteger)index subString:(NSString*)subString downLoadCount:(NSInteger)downLoadCount name:(NSString*)name section_videoid:(NSString*)section_videoid{
    if (_isDownloading) {
        return ;
    }
       __weak typeof(self) weakSelf = self;
    //更新当前下载的url
    NSLog(@"当前的url:%@",url);
    [self.dbManger UpdateDataWithTabelName:kDBTableName currentUrl:url section_videoid:section_videoid];
    
    [[WKDownLoadManger defaultInstance]downloadFileWithUrl:url progressHandler:^(NSProgress * _Nonnull downloadProgress) {
        
        _downLoadRecode = YES;
        if (_isDownloading) {
            _downLoadRecode = NO;
            return ;
        }
        if (downloadProgress.fractionCompleted == 1) {
            
        }
       // NSLog(@"已下载总个数:%ld",_index+1);
        //NSLog(@"下载总个数：%ld",(long)downLoadCount);
    } completeHandler:^(NSURLResponse * _Nullable response, NSString * _Nullable filePath) {
         _downLoadRecode = YES;
        if (_isDownloading) {
            _downLoadRecode = NO;
            return ;
        }
        _index++;
        [self.dbManger UpdateDataWithTabelName:kDBTableName completeCount:[NSString stringWithFormat:@"%ld",_index] section_videoid:section_videoid];
        if (_index+1 >= downLoadCount) {
            [self.dbManger UpdateDataWithTabelName:kDBTableName status:@"finish" section_videoid:section_videoid];
            _downLoadRecode = NO;
        }
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@video",name]];
        NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:path];
        documentsDirectoryURL = [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        dispatch_async(dispatch_get_main_queue(), ^{
            [fileManager moveItemAtURL:[NSURL URLWithString:filePath] toURL:documentsDirectoryURL error:nil];
        });
        //TODO: 处理文本
        NSString *pathText = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        pathText = [pathText stringByAppendingPathComponent:[NSString stringWithFormat:@"%@video",name]];
        pathText = [pathText stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",@"order.m3u8"]];
        NSString *content = [[NSString alloc] initWithContentsOfFile:pathText encoding:NSUTF8StringEncoding error:nil];
//        NSLog(@"文本内容:%@",content);
        //替换 地址
        NSArray *array =  [subString componentsSeparatedByString:@"/"];
        content = [content stringByReplacingOccurrencesOfString:subString withString:array.lastObject];
        [content writeToFile:pathText atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
    } errorHandlerk:^(NSError * _Nonnull error) {
        
       // [weakSelf showCustomAlertMessage:@"网络错误"];
        
    }];
}
#pragma mark - 暂停下载
- (void)supendDownload{
    
    _isDownloading = YES;
    self.mainQueue = nil;
    self.main0peration = nil;
    [self.mainQueue cancelAllOperations];
    [self.main0peration cancel];
    [self.mainQueue setSuspended:YES];
    [[WKDownLoadManger defaultInstance]suspendDownLoad];
    
}
#pragma mark - 继续下载
- (void)continueDownload:(NSNotification *)notification{
//    if (_downLoadRecode) {
//        [self showCustomAlertMessage:@"当前有正在下载任务,暂不支持多任务下载!"];
//        return;
//    }
    _isDownloading = NO;
     __weak typeof(self) weakSelf = self;
    NSDictionary *dict = notification.userInfo;
    NSString *typeid = [self changeCgrade:dict[@"cgrade"]];
    //NSString *placeholderImage = [NSString stringWithFormat:@"%@%@",kMainUrl,dict[@"section_imgurl"]];
    // NSString *section_name = dict[@"section_name"];
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *mac = [WKUniversal macaddress];
    NSString *phpsessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"getnewplayurl" forKey:@"commandid"];
    [para setObject:dict[@"section_videoid"] forKey:@"videoid"];
    [para setObject:typeid forKey:@"typeid"];
    [para setObject:@"2" forKey:@"type"];
    [para setObject:dict[@"courseid"] forKey:@"courseid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:phpsessid forKey:@"phpsessid"];
    [para setObject:mac forKey:@"mac"];
    self.section_voiceid = dict[@"section_videoid"];
    NSLog(@"继续下载的参数%@",notification.userInfo);
    self.mainQueue = [[NSOperationQueue alloc] init];
    //2.创建NSBlockOperation对象
    self.main0peration = [NSBlockOperation blockOperationWithBlock:^{
        [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
        [[WKNetworkTools shareManger]RunNoneRequest:para path:kServerDomain tip:nil completionHandler:^(id responseObject) {
        } errorHandler:^(NSError *error) {
            NSLog(@"继续下载错误%@",error);
        } finishHandler:^(id responseObject) {
            NSDictionary *dic = [responseObject mj_JSONObject];
            NSLog(@"继续下载接口:%@",dic);
           // NSDictionary *headDict = dic[@"head"];
            NSDictionary *bodyDict = dic[@"body"];
           // NSString *statuscode = headDict[@"statuscode"];
            NSString *vurl = bodyDict[@"vurl"];
            
        ////获取m3u8文件
            NSURL *url = [NSURL URLWithString:vurl];
            NSError *error = nil;
            NSStringEncoding encoding;
            NSString *content = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error];
            
            NSString *regulaStr = @"\\bhttp?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
            NSError *errorr = NULL;
            NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&errorr];
            NSArray *arrayOfAllMatches = [regex matchesInString:content options:0 range:NSMakeRange(0, [content length])];
            NSMutableArray *downloadUrlList = [NSMutableArray array];
        
        NSArray *dbDownLoadList = [weakSelf.dbManger QueryDataWithTableName:kDBTableName section_videoid:dict[@"section_videoid"]].mutableCopy;
            WKDownLoadModel *model = dbDownLoadList.firstObject;
            
            for (NSInteger i = 0; i<arrayOfAllMatches.count; i++){
                NSTextCheckingResult *match = arrayOfAllMatches[i];
                NSString* substringForMatch = [content substringWithRange:match.range];
                if (i>=([model.completeCount integerValue]-1)) {
                    [downloadUrlList addObject:substringForMatch];
                }
            }
            NSArray *downloadArray =downloadUrlList.mutableCopy;
            NSLog(@"要继续下载的url：%@",downloadArray);
            for (NSInteger i = 0; i<downloadArray.count; i++) {
                NSString *tsUrl = downloadArray[i];
                //继续下载TS文件
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [weakSelf continueDownTsWithTSUrl:tsUrl dict:dict m3u8Content:content];
                });
            }
           // NSLog(@"要继续下载的url：%@",downloadUrlList);
        }];
        
    }];
    [self.main0peration addExecutionBlock:^{
        
    }];
    self.mainQueue.maxConcurrentOperationCount = 1;
    //4.队列添加任务
    [self.mainQueue addOperation:self.main0peration];
}
- (void)continueDownTsWithTSUrl:(NSString*)TSurl dict:(NSDictionary*)dict m3u8Content:(NSString*)content{
    NSArray *dbDownLoadList = [self.dbManger QueryDataWithTableName:kDBTableName section_videoid:dict[@"section_videoid"]].mutableCopy;
    WKDownLoadModel *model = dbDownLoadList.firstObject;
    _index = [model.completeCount integerValue];
    self.downLoadCount = [model.totalCount integerValue];
    __weak typeof(self) weakSelf = self;
     [[WKDownLoadManger defaultInstance]downloadFileWithUrl:TSurl progressHandler:^(NSProgress * _Nonnull prograss) {
//         _downLoadRecode = YES;
         if (_isDownloading) {
             _downLoadRecode = NO;
             return ;
         }
     } completeHandler:^(NSURLResponse * _Nullable response, NSString * _Nullable filePath) {
//         _downLoadRecode = YES;
         if (_isDownloading) {
             _downLoadRecode = NO;
             return ;
         }
         _index++;
         NSLog(@"继续已下载总个数:%ld",_index+1);
         NSLog(@"继续下载总个数：%ld",(long)weakSelf.downLoadCount);
         [self.dbManger UpdateDataWithTabelName:kDBTableName completeCount:[NSString stringWithFormat:@"%ld",_index] section_videoid:dict[@"section_videoid"]];
         if (_index+1 >= weakSelf.downLoadCount) {
             [self.dbManger UpdateDataWithTabelName:kDBTableName status:@"finish" section_videoid: dict[@"section_videoid"] ];
             _downLoadRecode = NO;
         }
     NSLog(@"继续下载的文件名称：%ld",weakSelf.downLoadCount);
     NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
     path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@video",dict[@"section_name"]]];
     NSLog(@"继续下载的文件名称：%@",dict[@"section_name"]);
     NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:path];
     documentsDirectoryURL = [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename];
     NSFileManager *fileManager = [NSFileManager defaultManager];
     dispatch_async(dispatch_get_main_queue(), ^{
     [fileManager moveItemAtURL:[NSURL URLWithString:filePath] toURL:documentsDirectoryURL error:nil];
     });
     //TODO: 处理文本
     NSString *pathText = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
     pathText = [pathText stringByAppendingPathComponent:[NSString stringWithFormat:@"%@video",dict[@"section_name"]]];
     pathText = [pathText stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",@"order.m3u8"]];
     //替换原有的TS文件
     NSString *content = [NSString stringWithContentsOfFile:pathText encoding:NSUTF8StringEncoding error:nil];
         NSLog(@"要继续下载的m3u8：%@",content);
     //NSString *content = [[NSString alloc] initWithContentsOfFile:pathText encoding:NSUTF8StringEncoding error:nil];
     //替换 地址
     
     NSArray *array =  [TSurl componentsSeparatedByString:@"/"];
     content = [content stringByReplacingOccurrencesOfString:TSurl withString:array.lastObject];
     [content writeToFile:pathText atomically:YES encoding:NSUTF8StringEncoding error:nil];

     } errorHandlerk:^(NSError * _Nonnull error) {
     
     }];
    
}
- (void)didCreateJSContext:(NSNotification *)notification {
    
    NSString *indentifier = [NSString stringWithFormat:@"indentifier%lud", (unsigned long)self.webView.hash];
    NSString *indentifierJS = [NSString stringWithFormat:@"var %@ = '%@'", indentifier, indentifier];
    [self.webView stringByEvaluatingJavaScriptFromString:indentifierJS];
    
    JSContext *context = notification.object;
    
    if (![context[indentifier].toString isEqualToString:indentifier]) return;
    
    _context = context;
    MyJSObject *jsObject = [MyJSObject objectWithWebView:self.webView];
    _context[@"SendToJs"] = jsObject;
    jsObject.delegate = self;
}
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    webView.frame = CGRectMake(0, 65, kDeviceScreenWidth, kDeviceScreenHeight-65);
    self.progressView.hidden = NO;
    self.progressView.frame = CGRectMake(0, 64, kDeviceScreenWidth, 1);
    NSLog(@"---------------%@",request.URL);
    
    return YES;
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
    
     [self.progressView setProgress:0.6 animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    webView.frame = CGRectMake(0, 64, kDeviceScreenWidth, kDeviceScreenHeight-65);
     [self.progressView setProgress:1 animated:YES];
    self.progressView.hidden = YES;
    [self middleTitleColor:[UIColor whiteColor]];
    
   NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"标题:%@",title);
    if ([title isEqualToString:@"德智微课堂"]) {
        self.btnBack.hidden = YES;
        self.navgationBar.hidden = NO;
        self.btnUser.hidden = NO;
        self.progressView.frame = CGRectMake(0, 64, kDeviceScreenWidth, 1);
        self.webView.frame = CGRectMake(0, 65, kDeviceScreenWidth, kDeviceScreenHeight-64);
        //导航栏不用变
    }else if ([title isEqualToString:@"none"]){
        //导航栏隐藏
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        self.btnBack.hidden = NO;
        self.statusbar.backgroundColor = RGBColor(40, 188, 203);
        self.navgationBar.hidden = YES;
        self.progressView.frame = CGRectMake(0, 20, kDeviceScreenWidth, 1);
        self.webView.frame = CGRectMake(0, 21, kDeviceScreenWidth, kDeviceScreenHeight-64);
        if (_isCollection) {
            
            self.TFsearch.hidden = YES;
            self.btnSearch.hidden = YES;
            self.imgSearch.hidden = YES;
            self.downBtn.hidden = YES;
            self.btnScaner.hidden = YES;
            self.btnUser.hidden = YES;
            self.navgationBar.hidden = YES;
            self.progressView.frame = CGRectMake(0, 20, kDeviceScreenWidth, 1);
            self.webView.frame = CGRectMake(0, 21, kDeviceScreenWidth, kDeviceScreenHeight-64);

        }
        
    }else{
        //显示返回箭头和标题 把标题设置为H5的标题
        self.btnBack.hidden = NO;
        self.statusbar.backgroundColor = RGBColor(40, 188, 203);
        self.navgationBar.hidden = NO;
        self.TFsearch.hidden = YES;
        self.btnSearch.hidden = YES;
        self.imgSearch.hidden = YES;
        self.downBtn.hidden = YES;
        self.btnScaner.hidden = YES;
        self.btnUser.hidden = YES;
        self.navItem.title = title;
        self.progressView.frame = CGRectMake(0, 64, kDeviceScreenWidth, 1);
        self.webView.frame = CGRectMake(0, 65, kDeviceScreenWidth, kDeviceScreenHeight-64);
        if (((UIWebView *)self.webView).canGoBack) {
            self.btnClose.hidden = NO;
        }
        NSLog(@"标题长度:%ld",title.length);
        if (_isCanner) {
            self.navgationBar.hidden = YES;
            self.webView.frame = CGRectMake(0, 21, kDeviceScreenWidth, kDeviceScreenHeight-20);
            self.progressView.frame = CGRectMake(0, 20, kDeviceScreenWidth, 1);
        }
//        self.navItem.title = @"微资讯";
        if (title.length>12) {
            NSString *newTitle = [title substringToIndex:6];
            NSString *titleDeal = [NSString stringWithFormat:@"%@...",newTitle];
           self.navItem.title = titleDeal;
        }
    }
}

#pragma mark - webView回到主页
- (void)backJSAction:(NSNotification*)nofi{
__weak typeof(self) weakSelf = self;
    NSDictionary *dict = nofi.userInfo;
    NSString *status = dict[@"status1"];
    
    if (_isCanner) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:NO completion:nil];
        });
       
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([status isEqualToString:@"1"]) {
                if (weakSelf.collectionBlock) {
                    weakSelf.collectionBlock();
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        });
    }
}
#pragma mark - 系统返回手势
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    return YES;
    
}
- (void)backMainAction{
    
    [self.progressView setProgress:0 animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.webView.delegate = nil;
    self.webView.scrollView.delegate = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
        WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
        mainVC.userId = userid;
        WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
        [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
    });
}
#pragma mark - webView返回上一级
- (void)backClick{
//    __weak typeof(self) weakSelf = self;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        self.navItem.title = @"";
        self.TFsearch.hidden = NO;
        self.btnClose.hidden = YES;
        self.downBtn.hidden = NO;
        self.btnScaner.hidden = NO;
        self.imgSearch.hidden = NO;
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
             [self backAction];
        });
    }
}
#pragma mark - 跳转到个人中心
- (void)pushUserInfo:(UIButton*)sender{
    
   [MobClick profileSignInWithPUID:@"main_usercenter"];
    WKProfireViewController *profireVC = [[WKProfireViewController alloc]init];
    WKNavgationController *nav = [[WKNavgationController alloc] initWithRootViewController: profireVC];
    [self presentViewController:nav animated:YES completion:nil];
    
}
#pragma mark - 进去搜索
- (void)enterSearchAction:(UIButton*)sender{
    [MobClick profileSignInWithPUID:@"search"];
    WKSearchViewController *searchVC = [[WKSearchViewController alloc]init];
    WKNavgationController *nav = [[WKNavgationController alloc] initWithRootViewController: searchVC];
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark - 二维码
- (void)scanerClick:(UIButton*)sender{
    [MobClick profileSignInWithPUID:@"main_scancode"];
    __weak typeof(self) weakSelf = self;
    HMScannerController *scannerVC = [HMScannerController scannerWithCardName:nil avatar:nil completion:^(NSString *urlString) {
        
        NSArray *strArr = [urlString componentsSeparatedByString:@"?"];
        NSString *idStr = strArr.lastObject;
        NSArray *subArr = [idStr componentsSeparatedByString:@"&"];
        NSString *temStr = subArr.firstObject;
        NSArray *temArr = [temStr componentsSeparatedByString:@"="];
        NSString *courseId = temArr.lastObject;
         NSLog(@"--------%@",courseId);
        NSString *urlStr = [NSString stringWithFormat:@"%@/andriodwk/course/courseid/%@/userid/%@",kTestMainUrl,courseId,weakSelf.userId];
        NSLog(@"--------%@",urlStr);
        
        WKHomeViewController *homeVC = [[WKHomeViewController alloc]init];
        homeVC.userId = weakSelf.userId;
        homeVC.urlStr = urlStr;
        homeVC.isCanner = YES;
        homeVC.navgationBar.hidden = YES;
        [weakSelf.navigationController pushViewController:homeVC animated:YES];
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
    }];
    [scannerVC setTitleColor:[UIColor blackColor] tintColor:RGBColor(40, 188, 203)];
    [self showDetailViewController:scannerVC sender:nil];
}
#pragma mark - 下载
- (void)downClick:(UIButton*)sender{
    [MobClick profileSignInWithPUID:@"main_download"];
    WKDownLoadViewController *downVC = [[WKDownLoadViewController alloc]init];
    downVC.isHome = YES;
    [self.navigationController pushViewController:downVC animated:YES];
}
- (AFURLSessionManager *)downLoadSession {
    if (_downLoadSession == nil) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        _downLoadSession = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    }
    return _downLoadSession;
}

- (UIButton *)btnUser{
    
    if (_btnUser == nil) {
        _btnUser = [UIButton  buttonWithType:UIButtonTypeCustom];
        _btnUser.frame = CGRectMake(5, (44-35)*0.5, 35, 35);
        [_btnUser setImage:IMG(@"icon_usercenter_normal") forState:UIControlStateNormal];
        [_btnUser setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _btnUser.titleLabel.font = [UIFont systemFontOfSize:15];
        [_btnUser addTarget:self action:@selector(pushUserInfo:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnUser;
}
- (UILabel *)redLabel{
    
    if (_redLabel == nil) {
        
        _redLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.btnUser.frame)-12, (44-35)*0.5+5, 5, 5)];
        _redLabel.backgroundColor = [UIColor redColor];
        _redLabel.layer.cornerRadius = 2.5;
        _redLabel.layer.masksToBounds = YES;
        
    }
    return _redLabel;
}
- (UIButton *)btnBack{
    
    if (_btnBack == nil) {
        _btnBack = [UIButton  buttonWithType:UIButtonTypeCustom];
        _btnBack.frame = CGRectMake(5, (44-35)*0.5, 35, 35);
        [_btnBack setImage:IMG(@"icon_return_white") forState:UIControlStateNormal];
        [_btnBack setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _btnBack.titleLabel.font = [UIFont systemFontOfSize:15];
        [_btnBack addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnBack;
}
- (UITextField *)TFsearch{
    
    if (_TFsearch == nil) {
        _TFsearch = [[UITextField alloc]initWithFrame:CGRectMake(45, 5, kDeviceScreenWidth - 45 -self.downBtn.width-35, self.navigationController.navigationBar.height - 10)];
        _TFsearch.clearButtonMode = UITextFieldViewModeWhileEditing;
        _TFsearch.placeholder = @"    知识点";
        _TFsearch.borderStyle = UITextBorderStyleNone;
        _TFsearch.backgroundColor = [UIColor whiteColor];
        [_TFsearch setAutocorrectionType:UITextAutocorrectionTypeNo];
        [_TFsearch setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        UIView *leftView = [[UIView alloc] init];
        leftView.frame = CGRectMake(0, 0, 15, 0);
        _TFsearch.leftView = leftView;
        _TFsearch.leftViewMode = UITextFieldViewModeAlways;
        _TFsearch.layer.cornerRadius = 15;
        _TFsearch.layer.masksToBounds = YES;
    }
    return _TFsearch;
}
- (UIButton *)imgSearch{
    
    if (_imgSearch == nil) {
        _imgSearch = [UIButton buttonWithType:UIButtonTypeCustom];
        [_imgSearch setImage:IMG(@"icon_main_title_search") forState:UIControlStateNormal];
        _imgSearch.frame = CGRectMake(5, (self.TFsearch.height-20)*0.5, 20, 20);
    }
    return _imgSearch;
}
- (UIButton *)btnSearch{
    
    if (_btnSearch == nil) {
        
        _btnSearch = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnSearch.frame = CGRectMake(CGRectGetMaxX(self.imgSearch.frame), 0, self.TFsearch.width - self.imgSearch.width, self.TFsearch.height);
        [_btnSearch addTarget:self action:@selector(enterSearchAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnSearch;
}
- (UIButton *)downBtn{
    
    if (_downBtn == nil) {
        _downBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        _downBtn.frame = CGRectMake(kDeviceScreenWidth - 35-35, (44-35)*0.5, 35,35);
        [_downBtn setImage:IMG(@"icon_download_normal") forState:UIControlStateNormal];
        [_downBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _downBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_downBtn addTarget:self action:@selector(downClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _downBtn;
}

- (UIButton *)btnScaner{
    
    if (_btnScaner == nil) {
        _btnScaner = [UIButton  buttonWithType:UIButtonTypeCustom];
        _btnScaner.frame = CGRectMake(kDeviceScreenWidth-35, (44-35)*0.5, 35, 35);
        [_btnScaner setImage:IMG(@"icon_scaner") forState:UIControlStateNormal];
        [_btnScaner setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _btnScaner.titleLabel.font = [UIFont systemFontOfSize:15];
        [_btnScaner addTarget:self action:@selector(scanerClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnScaner;
}
- (UIButton *)btnClose{
    
    if (_btnClose == nil) {
        _btnClose = [UIButton  buttonWithType:UIButtonTypeCustom];
        _btnClose.frame = CGRectMake(kDeviceScreenWidth -35-5, (44-35)*0.5, 35,35);
        [_btnClose  setTitle:@"关闭"  forState:UIControlStateNormal];
        [_btnClose setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _btnClose.titleLabel.font = [UIFont systemFontOfSize:15];
        [_btnClose addTarget:self action:@selector(backMainAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnClose;
}
- (NSString*)changeCgrade:(NSString*)cgrade{
    
    NSString *typeid;
    if ([cgrade isEqualToString:@"1037"]||[cgrade isEqualToString:@"1038"]||[cgrade isEqualToString:@"1039"]) {
        
        typeid = @"1";
    }else if ([cgrade isEqualToString:@"1036"]){
        
        typeid = @"xiaoxue";
    }else if ([cgrade isEqualToString:@"1040"]||[cgrade isEqualToString:@"1041"]||[cgrade isEqualToString:@"1042"]){
        
        typeid = @"2";
    }
    return typeid;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

@implementation NSObject (JSTest)

- (void)webView:(id)unuse didCreateJavaScriptContext:(JSContext *)ctx forFrame:(id)frame {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DidCreateContextNotification" object:ctx];
}

@end
